﻿// Decompiled with JetBrains decompiler
// Type: TaleWorlds.CampaignSystem.Issues.ScoutEnemyGarrisonsIssueBehavior
// Assembly: TaleWorlds.CampaignSystem, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: E85F8C15-4DF6-4E9C-A58A-29177E40D07A
// Assembly location: D:\steam\steamapps\common\Mount & Blade II Bannerlord\bin\Win64_Shipping_Client\TaleWorlds.CampaignSystem.dll

using Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using TaleWorlds.CampaignSystem.Actions;
using TaleWorlds.CampaignSystem.Conversation;
using TaleWorlds.CampaignSystem.Party;
using TaleWorlds.CampaignSystem.Settlements;
using TaleWorlds.Core;
using TaleWorlds.Localization;
using TaleWorlds.ObjectSystem;
using TaleWorlds.SaveSystem;

#nullable disable
namespace TaleWorlds.CampaignSystem.Issues
{
  public class ScoutEnemyGarrisonsIssueBehavior : CampaignBehaviorBase
  {
    private const IssueBase.IssueFrequency ScoutEnemyGarrisonsIssueFrequency = IssueBase.IssueFrequency.VeryCommon;
    private const int QuestDurationInDays = 15;

    public override void RegisterEvents()
    {
      CampaignEvents.OnCheckForIssueEvent.AddNonSerializedListener((object) this, new Action<Hero>(this.OnCheckForIssue));
    }

    public void OnCheckForIssue(Hero hero)
    {
      List<Settlement> settlements;
      if (this.ConditionsHold(hero, out settlements))
        Campaign.Current.IssueManager.AddPotentialIssueData(hero, new PotentialIssueData(new PotentialIssueData.StartIssueDelegate(this.OnStartIssue), typeof (ScoutEnemyGarrisonsIssueBehavior.ScoutEnemyGarrisonsIssue), IssueBase.IssueFrequency.VeryCommon, (object) settlements));
      else
        Campaign.Current.IssueManager.AddPotentialIssueData(hero, new PotentialIssueData(typeof (ScoutEnemyGarrisonsIssueBehavior.ScoutEnemyGarrisonsIssue), IssueBase.IssueFrequency.VeryCommon));
    }

    private bool ConditionsHold(Hero issueGiver, out List<Settlement> settlements)
    {
      settlements = new List<Settlement>();
      if (!issueGiver.MapFaction.IsKingdomFaction || !issueGiver.IsFactionLeader || issueGiver.IsMinorFactionHero || issueGiver.IsPrisoner || issueGiver.IsFugitive || issueGiver.GetMapPoint() == null)
        return false;
      Kingdom elementWithPredicate = Kingdom.All.GetRandomElementWithPredicate<Kingdom>((Func<Kingdom, bool>) (x => x.IsAtWarWith(issueGiver.MapFaction)));
      if (elementWithPredicate != null)
      {
        List<Settlement> list1 = elementWithPredicate.Settlements.Where<Settlement>((Func<Settlement, bool>) (x => ScoutEnemyGarrisonsIssueBehavior.SuitableSettlementCondition(x, issueGiver))).ToList<Settlement>();
        if (list1.Count >= 5)
        {
          List<Settlement> list2 = list1.OrderBy<Settlement, float>((Func<Settlement, float>) (y => issueGiver.GetMapPoint().Position2D.Distance(y.Position2D))).ToList<Settlement>();
          settlements = list2.Take<Settlement>(3).ToList<Settlement>();
          return true;
        }
      }
      return false;
    }

    private IssueBase OnStartIssue(in PotentialIssueData pid, Hero issueOwner)
    {
      return (IssueBase) new ScoutEnemyGarrisonsIssueBehavior.ScoutEnemyGarrisonsIssue(issueOwner, pid.RelatedObject as List<Settlement>);
    }

    public override void SyncData(IDataStore dataStore)
    {
    }

    private static bool SuitableSettlementCondition(Settlement settlement, Hero issueGiver)
    {
      if (!settlement.IsFortification || !settlement.MapFaction.IsAtWarWith(issueGiver.MapFaction))
        return false;
      return !settlement.IsUnderSiege || settlement.SiegeEvent.BesiegerCamp.LeaderParty.MapFaction != Hero.MainHero.MapFaction;
    }

    public class ScoutEnemyGarrisonsIssue : IssueBase
    {
      private const int MinimumRelationToTakeQuest = -10;
      [SaveableField(10)]
      private Settlement _settlement1;
      [SaveableField(20)]
      private Settlement _settlement2;
      [SaveableField(30)]
      private Settlement _settlement3;

      internal static void AutoGeneratedStaticCollectObjectsScoutEnemyGarrisonsIssue(
        object o,
        List<object> collectedObjects)
      {
        ((MBObjectBase) o).AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      protected override void AutoGeneratedInstanceCollectObjects(List<object> collectedObjects)
      {
        base.AutoGeneratedInstanceCollectObjects(collectedObjects);
        collectedObjects.Add((object) this._settlement1);
        collectedObjects.Add((object) this._settlement2);
        collectedObjects.Add((object) this._settlement3);
      }

      internal static object AutoGeneratedGetMemberValue_settlement1(object o)
      {
        return (object) ((ScoutEnemyGarrisonsIssueBehavior.ScoutEnemyGarrisonsIssue) o)._settlement1;
      }

      internal static object AutoGeneratedGetMemberValue_settlement2(object o)
      {
        return (object) ((ScoutEnemyGarrisonsIssueBehavior.ScoutEnemyGarrisonsIssue) o)._settlement2;
      }

      internal static object AutoGeneratedGetMemberValue_settlement3(object o)
      {
        return (object) ((ScoutEnemyGarrisonsIssueBehavior.ScoutEnemyGarrisonsIssue) o)._settlement3;
      }

      public override bool IsThereAlternativeSolution => false;

      public override bool IsThereLordSolution => false;

      protected override int RewardGold => 0;

      public override TextObject IssueBriefByIssueGiver
      {
        get
        {
          return new TextObject("{=rrCkJgtd}We don't know enough about the enemy, [ib:closed][if:convo_thinking]where they are strong and where they are weak. I don't want to lead a huge army through their territory on a wild goose hunt. We need someone to ride through there swiftly, scouting out their garrisons. Can you do this?");
        }
      }

      public override TextObject IssueAcceptByPlayer
      {
        get
        {
          TextObject parent = new TextObject("{=dGakGflE}Yes, your {?QUEST_GIVER.GENDER}ladyship{?}lordship{\\?}, I'll gladly do it.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.IssueOwner.CharacterObject, parent);
          return parent;
        }
      }

      public override TextObject IssueQuestSolutionExplanationByIssueGiver
      {
        get
        {
          TextObject explanationByIssueGiver = new TextObject("{=seEyGLMz}Go deep into {ENEMY} territory, to {SETTLEMENT_1}, {SETTLEMENT_2} and {SETTLEMENT_3}. [ib:hip][if:convo_normal]I want to know every detail about them, what sort of fortifications they have, whether the walls are well-manned or undergarrisoned, and any other enemy forces in the vicinity.");
          explanationByIssueGiver.SetTextVariable("ENEMY", this._settlement1.MapFaction.Name);
          explanationByIssueGiver.SetTextVariable("SETTLEMENT_1", this._settlement1.Name);
          explanationByIssueGiver.SetTextVariable("SETTLEMENT_2", this._settlement2.Name);
          explanationByIssueGiver.SetTextVariable("SETTLEMENT_3", this._settlement3.Name);
          return explanationByIssueGiver;
        }
      }

      public override TextObject IssueQuestSolutionAcceptByPlayer
      {
        get => new TextObject("{=g6P6nKIf}Consider it done, commander.");
      }

      public override TextObject Title => new TextObject("{=G79IzJsZ}Scout Enemy Garrisons");

      public override TextObject Description
      {
        get
        {
          TextObject parent = new TextObject("{=AdoaDR26}{QUEST_GIVER.LINK} asks you to scout {SETTLEMENT_1}, {SETTLEMENT_2} and {SETTLEMENT_3}.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.IssueOwner.CharacterObject, parent);
          parent.SetTextVariable("SETTLEMENT_1", this._settlement1.Name);
          parent.SetTextVariable("SETTLEMENT_2", this._settlement2.Name);
          parent.SetTextVariable("SETTLEMENT_3", this._settlement3.Name);
          return parent;
        }
      }

      public ScoutEnemyGarrisonsIssue(Hero issueOwner, List<Settlement> settlements)
        : base(issueOwner, CampaignTime.DaysFromNow(15f))
      {
        this._settlement1 = settlements[0];
        this._settlement2 = settlements[1];
        this._settlement3 = settlements[2];
      }

      protected override void OnGameLoad()
      {
      }

      protected override void HourlyTick()
      {
      }

      protected override QuestBase GenerateIssueQuest(string questId)
      {
        return (QuestBase) new ScoutEnemyGarrisonsIssueBehavior.ScoutEnemyGarrisonsQuest(questId, this.IssueOwner, this._settlement1, this._settlement2, this._settlement3);
      }

      public override IssueBase.IssueFrequency GetFrequency()
      {
        return IssueBase.IssueFrequency.VeryCommon;
      }

      protected override bool CanPlayerTakeQuestConditions(
        Hero issueGiver,
        out IssueBase.PreconditionFlags flag,
        out Hero relationHero,
        out SkillObject skill)
      {
        relationHero = (Hero) null;
        skill = (SkillObject) null;
        flag = IssueBase.PreconditionFlags.None;
        if ((double) issueGiver.GetRelationWithPlayer() < -10.0)
        {
          flag |= IssueBase.PreconditionFlags.Relation;
          relationHero = issueGiver;
        }
        if (Hero.MainHero.IsKingdomLeader)
          flag |= IssueBase.PreconditionFlags.MainHeroIsKingdomLeader;
        if (issueGiver.MapFaction.IsAtWarWith(Hero.MainHero.MapFaction))
          flag |= IssueBase.PreconditionFlags.AtWar;
        if (Clan.PlayerClan.Tier < 2)
          flag |= IssueBase.PreconditionFlags.ClanTier;
        if (Hero.MainHero.GetSkillValue(DefaultSkills.Scouting) < 30)
        {
          flag |= IssueBase.PreconditionFlags.Skill;
          skill = DefaultSkills.Scouting;
        }
        if (Hero.MainHero.MapFaction != this.IssueOwner.MapFaction)
          flag |= IssueBase.PreconditionFlags.NotInSameFaction;
        return flag == IssueBase.PreconditionFlags.None;
      }

      public override bool IssueStayAliveConditions()
      {
        bool flag = this._settlement1.MapFaction.IsAtWarWith(this.IssueOwner.MapFaction) && this._settlement2.MapFaction.IsAtWarWith(this.IssueOwner.MapFaction) && this._settlement3.MapFaction.IsAtWarWith(this.IssueOwner.MapFaction);
        if (!flag)
          flag = this.TryToUpdateSettlements();
        return flag && this.IssueOwner.MapFaction.IsKingdomFaction;
      }

      protected override float GetIssueEffectAmountInternal(IssueEffect issueEffect)
      {
        return issueEffect == DefaultIssueEffects.ClanInfluence ? -0.1f : 0.0f;
      }

      private bool TryToUpdateSettlements()
      {
        Kingdom elementWithPredicate = Kingdom.All.GetRandomElementWithPredicate<Kingdom>((Func<Kingdom, bool>) (x => x.IsAtWarWith(this.IssueOwner.MapFaction)));
        if (elementWithPredicate != null)
        {
          List<Settlement> list1 = elementWithPredicate.Settlements.Where<Settlement>((Func<Settlement, bool>) (x => ScoutEnemyGarrisonsIssueBehavior.SuitableSettlementCondition(x, this.IssueOwner))).ToList<Settlement>();
          if (list1.Count >= 5)
          {
            List<Settlement> list2 = list1.Take<Settlement>(3).ToList<Settlement>();
            this._settlement1 = list2[0];
            this._settlement2 = list2[1];
            this._settlement3 = list2[2];
            return true;
          }
        }
        return false;
      }

      protected override void CompleteIssueWithTimedOutConsequences()
      {
      }
    }

    public class ScoutEnemyGarrisonsQuest : QuestBase
    {
      [SaveableField(10)]
      private ScoutEnemyGarrisonsIssueBehavior.QuestSettlement _questSettlement1;
      [SaveableField(20)]
      private ScoutEnemyGarrisonsIssueBehavior.QuestSettlement _questSettlement2;
      [SaveableField(30)]
      private ScoutEnemyGarrisonsIssueBehavior.QuestSettlement _questSettlement3;
      [SaveableField(40)]
      private int _scoutedSettlementCount;
      [SaveableField(50)]
      private JournalLog _startQuestLog;

      internal static void AutoGeneratedStaticCollectObjectsScoutEnemyGarrisonsQuest(
        object o,
        List<object> collectedObjects)
      {
        ((MBObjectBase) o).AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      protected override void AutoGeneratedInstanceCollectObjects(List<object> collectedObjects)
      {
        base.AutoGeneratedInstanceCollectObjects(collectedObjects);
        collectedObjects.Add((object) this._questSettlement1);
        collectedObjects.Add((object) this._questSettlement2);
        collectedObjects.Add((object) this._questSettlement3);
        collectedObjects.Add((object) this._startQuestLog);
      }

      internal static object AutoGeneratedGetMemberValue_questSettlement1(object o)
      {
        return (object) ((ScoutEnemyGarrisonsIssueBehavior.ScoutEnemyGarrisonsQuest) o)._questSettlement1;
      }

      internal static object AutoGeneratedGetMemberValue_questSettlement2(object o)
      {
        return (object) ((ScoutEnemyGarrisonsIssueBehavior.ScoutEnemyGarrisonsQuest) o)._questSettlement2;
      }

      internal static object AutoGeneratedGetMemberValue_questSettlement3(object o)
      {
        return (object) ((ScoutEnemyGarrisonsIssueBehavior.ScoutEnemyGarrisonsQuest) o)._questSettlement3;
      }

      internal static object AutoGeneratedGetMemberValue_scoutedSettlementCount(object o)
      {
        return (object) ((ScoutEnemyGarrisonsIssueBehavior.ScoutEnemyGarrisonsQuest) o)._scoutedSettlementCount;
      }

      internal static object AutoGeneratedGetMemberValue_startQuestLog(object o)
      {
        return (object) ((ScoutEnemyGarrisonsIssueBehavior.ScoutEnemyGarrisonsQuest) o)._startQuestLog;
      }

      public override bool IsRemainingTimeHidden => false;

      public override TextObject Title => new TextObject("{=G79IzJsZ}Scout Enemy Garrisons");

      private TextObject _playerStartsQuestLogText
      {
        get
        {
          TextObject parent = new TextObject("{=8avwit9N}{QUEST_GIVER.LINK}, the army commander of {FACTION} has told you that they need detailed information about enemy fortifications and troop numbers of the enemy. {?QUEST_GIVER.GENDER}She{?}He{\\?} wanted you to scout {SETTLEMENT_1}, {SETTLEMENT_2} and {SETTLEMENT_3}.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          parent.SetTextVariable("FACTION", this.QuestGiver.MapFaction.EncyclopediaLinkWithName);
          parent.SetTextVariable("SETTLEMENT_1", this._questSettlement1.Settlement.EncyclopediaLinkWithName);
          parent.SetTextVariable("SETTLEMENT_2", this._questSettlement2.Settlement.EncyclopediaLinkWithName);
          parent.SetTextVariable("SETTLEMENT_3", this._questSettlement3.Settlement.EncyclopediaLinkWithName);
          return parent;
        }
      }

      private TextObject _settlementBecomeNeutralLogText
      {
        get
        {
          return new TextObject("{=wgX2nL5Z}{SETTLEMENT} is no longer in control of enemy. There is no need to scout that settlement.");
        }
      }

      private TextObject _armyDisbandedQuestCancelLogText
      {
        get => new TextObject("{=JiHaL6IV}Army has disbanded and your mission has been canceled.");
      }

      private TextObject _noLongerAllyQuestCancelLogText
      {
        get
        {
          TextObject parent = new TextObject("{=vTnSa9rr}You are no longer allied with {QUEST_GIVER.LINK}'s faction. Your agreement with {QUEST_GIVER.LINK} was terminated.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject _allTargetsAreNeutral
      {
        get
        {
          return new TextObject("{=LC2F84GR}None of the target settlements are in control of the enemy. Army Commander has canceled the mission.");
        }
      }

      private TextObject _scoutFinishedForSettlementWallLevel1LogText
      {
        get
        {
          return new TextObject("{=5kxDhBWk}Your scouts have returned from {SETTLEMENT}. According to their report {SETTLEMENT}'s garrison has {GARRISON_SIZE} men and walls are not high enough but can be useful with sufficient garrison support.");
        }
      }

      private TextObject _scoutFinishedForSettlementWallLevel2LogText
      {
        get
        {
          return new TextObject("{=GUqjL6xk}Your scouts have returned from {SETTLEMENT}. According to their report {SETTLEMENT}'s garrison has {GARRISON_SIZE} men and walls are high enough to defend against invaders.");
        }
      }

      private TextObject _scoutFinishedForSettlementWallLevel3LogText
      {
        get
        {
          return new TextObject("{=YErURO5l}Your scouts have returned from {SETTLEMENT}. According to their report {SETTLEMENT}'s garrison has {GARRISON_SIZE} men and walls are too high and hard to breach.");
        }
      }

      private TextObject _questSuccess
      {
        get => new TextObject("{=Qy7Zmmvk}You have successfully scouted the target settlements.");
      }

      private TextObject _questTimedOut
      {
        get => new TextObject("{=GzodT3vS}You have failed to scout the enemy settlements in time.");
      }

      public ScoutEnemyGarrisonsQuest(
        string questId,
        Hero questGiver,
        Settlement settlement1,
        Settlement settlement2,
        Settlement settlement3)
        : base(questId, questGiver, CampaignTime.DaysFromNow(15f), 0)
      {
        this._questSettlement1 = new ScoutEnemyGarrisonsIssueBehavior.QuestSettlement(settlement1, 0);
        this._questSettlement2 = new ScoutEnemyGarrisonsIssueBehavior.QuestSettlement(settlement2, 0);
        this._questSettlement3 = new ScoutEnemyGarrisonsIssueBehavior.QuestSettlement(settlement3, 0);
        this.SetDialogs();
        this.InitializeQuestOnCreation();
      }

      protected override void InitializeQuestOnGameLoad() => this.SetDialogs();

      protected override void SetDialogs()
      {
        this.OfferDialogFlow = DialogFlow.CreateDialogFlow("issue_classic_quest_start").NpcLine(new TextObject("{=lyGvyZK4}Very well. When you reach one of their fortresses, spend some time observing. Don't move on to the next one at once. You don't need to find me to report back the details, just send your messengers.")).Condition((ConversationSentence.OnConditionDelegate) (() => Hero.OneToOneConversationHero == this.QuestGiver)).Consequence(new ConversationSentence.OnConsequenceDelegate(this.QuestAcceptedConsequences)).CloseDialog();
        this.DiscussDialogFlow = DialogFlow.CreateDialogFlow("quest_discuss").NpcLine(new TextObject("{=x3TO0gkN}Is there any progress on the task I gave you?[ib:closed][if:convo_normal]")).Condition((ConversationSentence.OnConditionDelegate) (() => Hero.OneToOneConversationHero == this.QuestGiver)).Consequence((ConversationSentence.OnConsequenceDelegate) (() => Campaign.Current.ConversationManager.ConversationEndOneShot += new Action(MapEventHelper.OnConversationEnd))).BeginPlayerOptions().PlayerOption(new TextObject("{=W5ab31gQ}Soon, commander. We are still working on it.")).NpcLine(new TextObject("{=U3LR7dyK}Good. I'll be waiting for your messengers.[if:convo_thinking]")).CloseDialog().PlayerOption(new TextObject("{=v75k1FoT}Not yet. We need to make more preparations.")).NpcLine(new TextObject("{=zYKeYZAo}All right. Don't rush this but also don't wait too long.")).CloseDialog().EndPlayerOptions().CloseDialog();
      }

      private void QuestAcceptedConsequences()
      {
        this.StartQuest();
        this.AddTrackedObject((ITrackableCampaignObject) this._questSettlement1.Settlement);
        this.AddTrackedObject((ITrackableCampaignObject) this._questSettlement2.Settlement);
        this.AddTrackedObject((ITrackableCampaignObject) this._questSettlement3.Settlement);
        this._scoutedSettlementCount = 0;
        this._startQuestLog = this.AddDiscreteLog(this._playerStartsQuestLogText, new TextObject("{=jpBpwgAs}Settlements"), this._scoutedSettlementCount, 3);
      }

      protected override void RegisterEvents()
      {
        CampaignEvents.OnClanChangedKingdomEvent.AddNonSerializedListener((object) this, new Action<Clan, Kingdom, Kingdom, ChangeKingdomAction.ChangeKingdomActionDetail, bool>(this.OnClanChangedKingdom));
        CampaignEvents.ArmyDispersed.AddNonSerializedListener((object) this, new Action<Army, Army.ArmyDispersionReason, bool>(this.OnArmyDispersed));
        CampaignEvents.OnSettlementOwnerChangedEvent.AddNonSerializedListener((object) this, new Action<Settlement, bool, Hero, Hero, Hero, ChangeOwnerOfSettlementAction.ChangeOwnerOfSettlementDetail>(this.OnSettlementOwnerChanged));
      }

      protected override void HourlyTick()
      {
        if (!this.IsOngoing)
          return;
        List<ScoutEnemyGarrisonsIssueBehavior.QuestSettlement> questSettlementList = new List<ScoutEnemyGarrisonsIssueBehavior.QuestSettlement>()
        {
          this._questSettlement1,
          this._questSettlement2,
          this._questSettlement3
        };
        if (questSettlementList.TrueForAll((Predicate<ScoutEnemyGarrisonsIssueBehavior.QuestSettlement>) (x => !x.Settlement.MapFaction.IsAtWarWith(this.QuestGiver.MapFaction))))
        {
          this.AddLog(this._allTargetsAreNeutral);
          this.CompleteQuestWithCancel();
        }
        else
        {
          foreach (ScoutEnemyGarrisonsIssueBehavior.QuestSettlement questSettlement in questSettlementList)
          {
            if (!questSettlement.IsScoutingCompleted())
            {
              if ((double) Campaign.Current.Models.MapDistanceModel.GetDistance(MobileParty.MainParty, questSettlement.Settlement) <= (double) MobileParty.MainParty.SeeingRange)
              {
                ++questSettlement.CurrentScoutProgress;
                if (questSettlement.CurrentScoutProgress == 1)
                {
                  TextObject message = new TextObject("{=qfjRGjM4}Your scouts started to gather information about {SETTLEMENT}.");
                  message.SetTextVariable("SETTLEMENT", questSettlement.Settlement.Name);
                  MBInformationManager.AddQuickInformation(message);
                }
                else if (questSettlement.IsScoutingCompleted())
                {
                  this._startQuestLog.UpdateCurrentProgress(++this._scoutedSettlementCount);
                  this.RemoveTrackedObject((ITrackableCampaignObject) questSettlement.Settlement);
                  TextObject empty = TextObject.Empty;
                  TextObject text = questSettlement.Settlement.Town.GetWallLevel() != 1 ? (questSettlement.Settlement.Town.GetWallLevel() != 2 ? this._scoutFinishedForSettlementWallLevel3LogText : this._scoutFinishedForSettlementWallLevel2LogText) : this._scoutFinishedForSettlementWallLevel1LogText;
                  text.SetTextVariable("SETTLEMENT", questSettlement.Settlement.EncyclopediaLinkWithName);
                  MobileParty garrisonParty = questSettlement.Settlement.Town.GarrisonParty;
                  int totalHealthyCount = garrisonParty != null ? garrisonParty.MemberRoster.TotalHealthyCount : 0;
                  int militia = (int) questSettlement.Settlement.Militia;
                  text.SetTextVariable("GARRISON_SIZE", totalHealthyCount + militia);
                  this.AddLog(text);
                }
              }
              else
                questSettlement.ResetCurrentProgress();
            }
          }
          if (!questSettlementList.TrueForAll((Predicate<ScoutEnemyGarrisonsIssueBehavior.QuestSettlement>) (x => x.IsScoutingCompleted())))
            return;
          this.AllScoutingDone();
        }
      }

      private void OnSettlementOwnerChanged(
        Settlement settlement,
        bool openToClaim,
        Hero newOwner,
        Hero oldOwner,
        Hero capturerHero,
        ChangeOwnerOfSettlementAction.ChangeOwnerOfSettlementDetail detail)
      {
        List<ScoutEnemyGarrisonsIssueBehavior.QuestSettlement> questSettlementList = new List<ScoutEnemyGarrisonsIssueBehavior.QuestSettlement>()
        {
          this._questSettlement1,
          this._questSettlement2,
          this._questSettlement3
        };
        foreach (ScoutEnemyGarrisonsIssueBehavior.QuestSettlement questSettlement in questSettlementList)
        {
          if (settlement == questSettlement.Settlement && (newOwner.MapFaction == this.QuestGiver.MapFaction || !newOwner.MapFaction.IsAtWarWith(this.QuestGiver.MapFaction)))
          {
            questSettlement.IsCompletedThroughBeingNeutral = true;
            questSettlement.SetScoutingCompleted();
            this._startQuestLog.UpdateCurrentProgress(++this._scoutedSettlementCount);
            if (this.IsTracked((ITrackableCampaignObject) questSettlement.Settlement))
              this.RemoveTrackedObject((ITrackableCampaignObject) questSettlement.Settlement);
            TextObject becomeNeutralLogText = this._settlementBecomeNeutralLogText;
            becomeNeutralLogText.SetTextVariable("SETTLEMENT", questSettlement.Settlement.EncyclopediaLinkWithName);
            this.AddLog(becomeNeutralLogText);
            if (!questSettlementList.TrueForAll((Predicate<ScoutEnemyGarrisonsIssueBehavior.QuestSettlement>) (x => x.IsCompletedThroughBeingNeutral)))
              break;
            this.AddLog(this._allTargetsAreNeutral);
            this.CompleteQuestWithCancel();
            break;
          }
        }
      }

      private void OnArmyDispersed(Army army, Army.ArmyDispersionReason reason, bool isPlayersArmy)
      {
        if (army.ArmyOwner != this.QuestGiver)
          return;
        this.AddLog(this._armyDisbandedQuestCancelLogText);
        this.CompleteQuestWithCancel();
      }

      private void OnClanChangedKingdom(
        Clan clan,
        Kingdom oldKingdom,
        Kingdom newKingdom,
        ChangeKingdomAction.ChangeKingdomActionDetail detail,
        bool showNotification = true)
      {
        if (clan != Clan.PlayerClan || oldKingdom != this.QuestGiver.MapFaction)
          return;
        this.AddLog(this._noLongerAllyQuestCancelLogText);
        this.CompleteQuestWithCancel();
      }

      private void AllScoutingDone()
      {
        this.AddLog(this._questSuccess);
        GainRenownAction.Apply(Hero.MainHero, 3f);
        GainKingdomInfluenceAction.ApplyForDefault(Hero.MainHero, 10f);
        this.RelationshipChangeWithQuestGiver = 3;
        this.CompleteQuestWithSuccess();
      }

      protected override void OnTimedOut()
      {
        this.AddLog(this._questTimedOut);
        this.RelationshipChangeWithQuestGiver = -2;
      }
    }

    public class QuestSettlement
    {
      private const int CompleteScoutAfterHours = 8;
      [SaveableField(10)]
      public Settlement Settlement;
      [SaveableField(20)]
      public int CurrentScoutProgress;
      public bool IsCompletedThroughBeingNeutral;

      internal static void AutoGeneratedStaticCollectObjectsQuestSettlement(
        object o,
        List<object> collectedObjects)
      {
        ((ScoutEnemyGarrisonsIssueBehavior.QuestSettlement) o).AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      protected virtual void AutoGeneratedInstanceCollectObjects(List<object> collectedObjects)
      {
        collectedObjects.Add((object) this.Settlement);
      }

      internal static object AutoGeneratedGetMemberValueSettlement(object o)
      {
        return (object) ((ScoutEnemyGarrisonsIssueBehavior.QuestSettlement) o).Settlement;
      }

      internal static object AutoGeneratedGetMemberValueCurrentScoutProgress(object o)
      {
        return (object) ((ScoutEnemyGarrisonsIssueBehavior.QuestSettlement) o).CurrentScoutProgress;
      }

      public QuestSettlement(Settlement settlement, int currentScoutProgress)
      {
        this.Settlement = settlement;
        this.CurrentScoutProgress = currentScoutProgress;
        this.IsCompletedThroughBeingNeutral = false;
      }

      public bool IsScoutingCompleted() => this.CurrentScoutProgress >= 8;

      public void SetScoutingCompleted() => this.CurrentScoutProgress = 8;

      public void ResetCurrentProgress() => this.CurrentScoutProgress = 0;
    }

    public class ScoutEnemyGarrisonsIssueTypeDefiner : SaveableTypeDefiner
    {
      public ScoutEnemyGarrisonsIssueTypeDefiner()
        : base(97600)
      {
      }

      protected override void DefineClassTypes()
      {
        this.AddClassDefinition(typeof (ScoutEnemyGarrisonsIssueBehavior.ScoutEnemyGarrisonsIssue), 1);
        this.AddClassDefinition(typeof (ScoutEnemyGarrisonsIssueBehavior.ScoutEnemyGarrisonsQuest), 2);
        this.AddClassDefinition(typeof (ScoutEnemyGarrisonsIssueBehavior.QuestSettlement), 3);
      }
    }
  }
}
